package com.smalls.newvideotwo.base;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.smalls.newvideotwo.NewDTVApp;
import com.smalls.newvideotwo.R;
import com.smalls.newvideotwo.mvp.bean.ApkInfoItem;
import com.smalls.newvideotwo.mvp.presenter.GetApkInfoPresenter;
import com.smalls.newvideotwo.mvp.view.IGetApkInfoView;
import com.smalls.newvideotwo.service.FloatService;
import com.smalls.newvideotwo.util.EventUtil;
import com.smalls.newvideotwo.util.LogUtil;
import com.smalls.newvideotwo.utils.Constant;
import com.smalls.newvideotwo.utils.Tools;
import com.smalls.newvideotwo.view.BaseDialog;
import com.smalls.newvideotwo.view.FloatWindows;
import com.smalls.newvideotwo.view.NetworkConnectChangedReceiver;
import com.smalls.newvideotwo.view.NetworkDialog;
import com.uking.moudle.ukingplayer_info;
import com.uking.util.VKConstant;
import com.uking.ukingmodule.ukingjnic;

import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by thearyong on 2017/3/1.
 * activity 基类
 */

public abstract class BaseActivity extends FragmentActivity implements IGetApkInfoView {
    private static String TAG = Constant.baddcoolio2tag? Constant.TAGPREFIXSTR + BaseActivity.class.getSimpleName():BaseActivity.class.getSimpleName();
    private NetworkDialog mDlg=null;
    private boolean cancelUpdate = false;
    public static boolean bDownloadDone = false;
    public static int mDownloadVersion = 0;
    public static int mDownloadStatus = 0;
    public static final String HOME_DOWNLOAD_ACTION_COMPELETE = "wonderfulhome.download.compelete";
    public static final String DOWNLOAD_ACTION_COMPELETE="WonderfulVideo.download.compelet";//下载完成广播
    public static final String DOWNLOAD_ACTION_CANCEL="WonderfulVideo.download.cancel";//下载取消广播
    public static final String DOWNLOAD_ACTION_FAILED="WonderfulVideo.download.failed";//下载失败广播
    public static final String DOWNLOAD_ACTION_START="WonderfulVideo.download.start";//下载开始广播
    private static final int CHECK_UPDATE = 2;
    private GetApkInfoPresenter getApkInfoPresenter = new GetApkInfoPresenter(this);
    protected Intent mFloatService;
    protected Toast mExitHintToast;
    protected long mExitTime = 0;
    protected int mErrorCode = 0;
    protected BaseDialog mErrorDialog;
    protected NetworkConnectChangedReceiver mNetworkConnectChangedReceiver;
    protected BaseDialog mNetworkHintDialog;

    private Handler mHander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CHECK_UPDATE:
                {
                    getApkInfoPresenter.requestData(false);
                    break;
                }
            }
        }
    };

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(DOWNLOAD_ACTION_COMPELETE)) {
                Log.i(TAG,"DOWNLOAD_ACTION_COMPELETE!!!");
                ApkInfoItem infoItem = (ApkInfoItem) intent.getSerializableExtra("apk");
                installApk(infoItem);
            } else if(intent.getAction().equals(DOWNLOAD_ACTION_FAILED)) {
                Log.i(TAG,"DOWNLOAD_ACTION_FAILED!!!");
            }
        }
    };

    @LayoutRes
    public abstract int onSetContentView();

    protected void startFloatService() {
        this.mFloatService = new Intent(this, FloatService.class);
        startService(this.mFloatService);
    }
    public void replaceFragment(@IdRes int resID, Fragment fragment) {
        getSupportFragmentManager().beginTransaction().replace(resID, fragment).commitAllowingStateLoss();
    }
    protected void stopFloatService() {
        if (this.mFloatService == null) {
            this.mFloatService = new Intent(this, FloatService.class);
        }
        stopService(this.mFloatService);
        Log.d(this.TAG, "stopFloatService");
    }

    public void onBackPressed() {
        if (this.TAG.equalsIgnoreCase("MainActivity")) {
            pressAgain2Exits();
        } else {
            super.onBackPressed();
        }
    }

    private void pressAgain2Exits() {
        Log.d(this.TAG, "pressAgain2Exits");
        if (System.currentTimeMillis() - this.mExitTime > 2000) {
            cancelExitHintToast();
            this.mExitHintToast = Toast.makeText(this, getString(R.string.press_again_to_exits), Toast.LENGTH_SHORT);
            this.mExitHintToast.show();
            this.mExitTime = System.currentTimeMillis();
            return;
        }
        Log.d(this.TAG, " super.onBackPressed()");
        cancelExitHintToast();
        super.onBackPressed();
        //new ukingjnic().destroyDlownloadModul(this.playType);
    }

    protected void cancelExitHintToast() {
        if (this.mExitHintToast != null) {
            this.mExitHintToast.cancel();
        }
    }
    protected void initView(Bundle savedInstanceState) {

    }

    protected void setListener() {
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(onSetContentView());
        BaseActivityManager.getInstance().addActivity(this);
        initView(savedInstanceState);
        setListener();
        Log.i("BaseActivity", "class name activity: " + this.getClass().getName());
    }

    protected void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    public void startActivity(Class mClass) {
        startActivity(new Intent(this, mClass));
    }

    @Subscribe
    public void onEvent(Object obj) {
        // 必须要是public才能收到
        // 方法名无所谓，只要带上Subscribe，在线程里发送注解要添加ThreadMode
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventUtil.register(this);
    }

    @Override
    protected void onDestroy() {
        BaseActivityManager.getInstance().finishActivity(this);
        super.onDestroy();
        EventUtil.unregister(this);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @SuppressWarnings("static-access")
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                    ConnectivityManager connectMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
                    NetworkInfo networkInfo = connectMgr.getActiveNetworkInfo();
                    if (networkInfo != null && networkInfo.isAvailable()) {
						/*
						 * network is ok.
						 */
                        Log.d(TAG, "NET UP  network is ok.");
                        if (mDlg != null && mDlg.isShowing()) {
                            mDlg.dismiss();
                        }

                    } else {


                        Log.e(TAG, "NET DOWN");
                        if (mDlg == null) {
                            LogUtil.e(TAG, "mDlg == null NET DOWN");
                            mDlg = new NetworkDialog(BaseActivity.this,
                                    R.style.dialog);
                            mDlg.setNegativeButtonListener(networkExitBotton);
                            mDlg.setPositiveButtonListener(networkSettingBotton);
                            mDlg.show();
                        } else {
                            LogUtil.e(TAG, "mDlg != null NET DOWN");
                            mDlg.show();
                        }

                    }

                }
            } catch (Exception e) {
                Log.e(TAG, "error");
            }
        }
    };


    private void registerNetworkReceiver() {
        IntentFilter filter = new IntentFilter(
                ConnectivityManager.CONNECTIVITY_ACTION);
        this.registerReceiver(receiver, filter);
    }

    private void unRegisterNetworkReceiver() {
        this.unregisterReceiver(receiver);
    }

    private NetworkDialog.DialogButtonListener networkExitBotton = new NetworkDialog.DialogButtonListener() {

        @Override
        public void onClick(Dialog dlg, View v) {
            // TODO Auto-generated method stub
            if (mDlg != null) {
                mDlg.dismiss();
                BaseActivity.this.finish();
            }
        }
    };

    private NetworkDialog.DialogButtonListener networkSettingBotton = new NetworkDialog.DialogButtonListener() {

        @Override
        public void onClick(Dialog dlg, View v) {
            // TODO Auto-generated method stub
            Intent resolveIntent = new Intent();
            resolveIntent.setClassName("com.android.settings",
                    "com.android.settings.Settings");
            startActivity(resolveIntent);

            if (mDlg != null) {
                mDlg.dismiss();
            }
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        unRegisterNetworkReceiver();
        unregisterReceiver(mReceiver);
        mHander.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerNetworkReceiver();
        IntentFilter mFilter = new IntentFilter();// 监听应用安装和卸载的广播以便刷新界面
        mFilter.addAction(DOWNLOAD_ACTION_COMPELETE);
        mFilter.addAction(DOWNLOAD_ACTION_FAILED);
        registerReceiver(mReceiver, mFilter);

        mHander.sendEmptyMessage(CHECK_UPDATE);
    }

    private int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            versionCode = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    @Override
    public void onSucceedGetApkInfo(ApkInfoItem getChannelsResult, int i) {
        if(getChannelsResult!=null) {
            int versioncode = getVersionCode(BaseActivity.this);
            Log.i(TAG,"CHECK_UPDTAE versioncode="+versioncode
                    +" updateInfo.getVersioncode()="+getChannelsResult.getVersioncode());
            if(versioncode<Integer.valueOf(getChannelsResult.getVersioncode())
                    &&getChannelsResult.getApk_path()!=null) {
                if(bDownloadDone
                        &&mDownloadVersion==Integer.valueOf(getChannelsResult.getVersioncode())) {
                    mHander.sendEmptyMessageDelayed(CHECK_UPDATE,10*60*1000);
                    return;
                }
                if(mDownloadStatus!=1&&mDownloadStatus!=2) {
                    Toast.makeText(NewDTVApp.getApp(), getString(R.string.force_update), Toast.LENGTH_LONG).show();
                    downloadApk(getChannelsResult.getApk_path());
                    mDownloadVersion=Integer.valueOf(getChannelsResult.getVersioncode());
                }
            } else {
                mHander.sendEmptyMessageDelayed(CHECK_UPDATE,10*60*1000);
            }
        }
    }

    @Override
    public void showErrDialogGetApkInfo(String str, int i) {
        mHander.sendEmptyMessageDelayed(CHECK_UPDATE,10*60*1000);
    }

    private void downloadApk(String url) {
        File file = null;
        Log.i(TAG,"downloadApk url="+url);

        file = new File(this.getFilesDir() + "/download");
        if (!file.exists() || file.isFile()) {
            file.mkdirs();
            chmodPath(file.getAbsolutePath());
        }


        ApkInfoItem appInfo = new ApkInfoItem();
        appInfo.setPackageName(this.getPackageName());
        appInfo.setApk_path(url);
        appInfo.setFile(file.getAbsolutePath() + "/" + appInfo.getPackageName() + ".apk");

        File apkFile = new File(appInfo.getFile());
        Log.e("判断文件是否存在", "paht="+appInfo.getFile());
        if (!apkFile.exists()) {
            Log.e("文件是否存在", "文件不存在！");
            try {
                apkFile.createNewFile();//测试是否有新建文件的权限
                chmodPath(appInfo.getFile());
                apkFile.delete();
            } catch (Exception e) {
                // TODO: handle exception
                File f = new File(this.getFilesDir().toString());//若无全向则直接下载
                appInfo.setFile(f.getAbsolutePath() + "/" + appInfo.getPackageName() + ".apk");
            }
        } else {
            deleteApk(apkFile);
        }
        cancelUpdate=false;
        new downloadApkThread(this,appInfo).start();
        mDownloadStatus = 1;
    }
    private class downloadApkThread extends Thread {
        private ApkInfoItem appInfo = null;
        private Context mContext;
        private FloatWindows mFloadtWindows = null;

        public downloadApkThread(Context context,ApkInfoItem appInfo){
            this.mContext = context;
            this.appInfo=appInfo;
            mFloadtWindows = new FloatWindows();
            mFloadtWindows.initFloat();
        }
        public void run() {
            Intent intent=null;
            try {
                if(appInfo==null)
                    return;
                URL url = new URL(appInfo.getApk_path());
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.setRequestProperty("User-Agent", "Crowne");
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();

                File apkFile = new File(appInfo.getFile());
                apkFile.createNewFile();
                chmodPath(apkFile.getAbsolutePath());

                RandomAccessFile fos = new RandomAccessFile(appInfo.getFile(), "rw");
                byte buf[] = new byte[1024];
                int count = 0;
                do {
                    int numread = is.read(buf);
                    count += numread;
                    if (numread <= 0) {
                        bDownloadDone = true;
                        if(mFloadtWindows!=null) {
                            mFloadtWindows.onFinish(count);
                        }
                        Log.i(TAG,"download finish!");
                        if(Tools.isServiceRunning2(BaseActivity.this,"com.smalls.wonderfulhome.Service.InstallService")) {
                            intent = new Intent(HOME_DOWNLOAD_ACTION_COMPELETE);// 当前context下载完成广播
                            intent.putExtra("start",true);
                            intent.putExtra("pname",appInfo.getPackageName());
                            intent.putExtra("apk", appInfo.getFile());
                        } else {
                            Log.i(TAG,"InstallService no running!");
                            intent = new Intent(DOWNLOAD_ACTION_COMPELETE);// 当前context下载完成广播
                            intent.putExtra("apk", appInfo);
                        }
                        mDownloadStatus = 2;
                        break;
                    }
                    fos.write(buf, 0, numread);
                    if(mFloadtWindows!=null) {
                        mFloadtWindows.onProgress(count,length);
                    }
                } while (!cancelUpdate);
                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                intent=new Intent(DOWNLOAD_ACTION_FAILED);
                intent.putExtra("pkg", appInfo.getPackageName());
                e.printStackTrace();
                mDownloadVersion = 0;
                mDownloadStatus = 3;
            } catch (IOException e) {
                intent=new Intent(DOWNLOAD_ACTION_FAILED);
                intent.putExtra("pkg", appInfo.getPackageName());
                e.printStackTrace();
                mDownloadVersion = 0;
                mDownloadStatus = 3;
            }
            if(intent!=null){
                mContext.sendBroadcast(intent);
            }
            if(mFloadtWindows!=null) {
                mFloadtWindows.releaseFloat();
            }
        }
    }

    public static boolean chmodPath(String path) {
        boolean issuccess = false;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("chmod 777 " + path);
            issuccess = process.waitFor() == 0;
        } catch (Exception e) {
            e.printStackTrace();
            issuccess = false;
        }
        return issuccess;
    }

    private void deleteApk(File apkfile)	{
        if(apkfile.exists())
            apkfile.delete();
    }
    public void installApk(ApkInfoItem item) {
        Log.i(TAG,"installApk ");
        File apkfile = new File(item.getFile());
        if (!apkfile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                "application/vnd.android.package-archive");
        this.startActivity(i);
        mDownloadStatus = 0;
    }

    public void installApk() {
        Log.i(TAG,"installApk ");
        File file;
        file = new File(this.getFilesDir() + "/download"+ "/" + getPackageName() + ".apk");

        if (!file.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + file.toString()),
                "application/vnd.android.package-archive");
        this.startActivity(i);
        mDownloadStatus = 0;
    }

    public int getErrorCode() {
        return this.mErrorCode;
    }

    public void setErrorCode(int mErrorCode) {
        this.mErrorCode = mErrorCode;
    }

    public void showErrorToastDialog(int errorCode, boolean isLive) {
        String errorStr = null;
        switch (errorCode) {
            case 1 /*1*/:
                errorStr = getString(R.string.rs_error_net_exception) + "1";
                break;
            case 20000 /*20000*/:
                errorStr = getString(R.string.rs_error_code_connect_timeout) + "1" + getString(R.string.rs_error_code_connect_retry);
                break;
            case VKConstant.AAA_BOX_TIMEOUT_ERROR /*20100*/:
                errorStr = getString(R.string.rs_error_code_connect_timeout) + "2" + getString(R.string.rs_error_code_connect_retry);
                break;
            case VKConstant.AAA_EPG4B_TIMEOUT_ERROR /*20200*/:
                errorStr = getString(R.string.rs_error_code_connect_timeout) + "3" + getString(R.string.rs_error_code_connect_retry);
                break;
            case VKConstant.AAA_PARSE_ERROR /*20210*/:
                errorStr = getString(R.string.rs_error_code_connect_timeout) + "4" + getString(R.string.rs_error_code_connect_retry);
                break;
            case VKConstant.EPG4B_NOPRODUCT_ERROR /*20300*/:
                errorStr = getString(R.string.rs_error_code_connect_timeout) + "5" + getString(R.string.rs_error_code_connect_retry);
                break;
            case VKConstant.ZHONGJIANJIAN_LOW_ERROR /*20400*/:
                errorStr = getString(R.string.rs_error_code_connect_timeout) + "6" + getString(R.string.rs_error_code_connect_retry);
                break;
            case VKConstant.ZHONGJIANJIAN_DATA_ERROR /*20500*/:
                errorStr = getString(R.string.rs_error_code_connect_timeout) + "7" + getString(R.string.rs_error_code_connect_retry);
                break;
            case VKConstant.BOX_GSLB_TIMEOUT_ERROR /*20600*/:
                errorStr = getString(R.string.rs_error_code_play_timeout) + "1" + getString(R.string.rs_error_code_play_retry);
                break;
            case VKConstant.BOX_EMS_TIMEOUT_ERROR /*20700*/:
                errorStr = getString(R.string.rs_error_code_play_timeout) + "2" + getString(R.string.rs_error_code_play_retry);
                break;
            case VKConstant.EMS_LOW_RESOURCES_ERROR /*20800*/:
                errorStr = getString(R.string.rs_error_code_play_timeout) + "3" + getString(R.string.rs_error_code_play_retry);
                break;
            case VKConstant.GSLB_NO_DATA_ERROR /*20900*/:
                errorStr = getString(R.string.rs_error_code_play_timeout) + "4" + getString(R.string.rs_error_code_play_retry);
                break;
            case VKConstant.ZHONGJJ_MALOOC_ERROR /*21000*/:
                errorStr = getString(R.string.rs_error_code_play_timeout) + "5" + getString(R.string.rs_error_code_play_retry);
                break;
            case VKConstant.ZHONGJJ_EXIT_ERROR /*21010*/:
                errorStr = getString(R.string.rs_error_code_play_timeout) + "6" + getString(R.string.rs_error_code_play_retry);
                break;
            case VKConstant.BANDWIDTH_ERROR /*21100*/:
                errorStr = getString(R.string.rs_error_code_play_timeout) + "7" + getString(R.string.rs_error_code_play_retry);
                break;
            case ukingplayer_info.ukingMSG_UNAUTH_ERROR /*21500*/:
                errorStr = getString(R.string.rs_error_code_play_timeout) + "8" + getString(R.string.rs_error_code_play_retry);
                break;
            case ukingplayer_info.ukingMSG_LICENSE_EXPIRED /*21600*/:
                errorStr = getString(R.string.rs_error_code_play_timeout) + "9" + getString(R.string.rs_error_code_play_retry);
                break;
            case ukingplayer_info.ukingMSG_RESOURCE_NOT_FOUND /*21700*/:
                errorStr = getString(R.string.rs_error_code_play_timeout) + "10" + getString(R.string.rs_error_code_play_retry);
                break;
            case ukingplayer_info.ukingMSG_NO_PUSH_TSTREAM /*21710*/:
                errorStr = getString(R.string.rs_error_code_play_timeout) + "11" + getString(R.string.rs_error_code_play_retry);
                break;
            case VKConstant.LICENSE_EXPIRED /*23000*/:
                errorStr = getString(R.string.rs_error_code_connect_timeout) + "8" + getString(R.string.rs_error_code_connect_retry);
                break;
            case VKConstant.NOT_USE_IN_BUY_PLACE /*24000*/:
                errorStr = getString(R.string.rs_error_code_connect_timeout) + "9" + getString(R.string.rs_error_code_connect_retry);
                break;
            case VKConstant.NO_MORE_THAN_SET_TIME /*90000*/:
                errorStr = getString(R.string.rs_error_code_connect_timeout) + "10" + getString(R.string.rs_error_code_connect_retry);
                break;
            case VKConstant.NO_GET_NET_TIME /*90001*/:
                errorStr = getString(R.string.rs_error_code_connect_timeout) + "11" + getString(R.string.rs_error_code_connect_retry);
                break;
        }
        if (!TextUtils.isEmpty(errorStr)) {
            showErrorDialog(errorStr, errorCode);
        }
    }

    protected void showErrorDialog(final String msg, int errorCode) {
        if (!TextUtils.isEmpty(msg) && !isFinishing()) {
            cancelErrorDialog();
            if (this.mErrorDialog == null) {
                this.mErrorDialog = new BaseDialog(this);
                this.mErrorDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    public void onCancel(DialogInterface dialog) {
                        BaseActivity.this.onErrorToastDialogCancel(msg);
                    }
                });
            }
            this.mErrorDialog.setMessage(msg);
            this.mErrorCode = errorCode;
            this.mErrorDialog.show();
        }
    }

    protected void onErrorToastDialogCancel(String msg) {
        this.mErrorCode = 0;
    }

    public void cancelErrorDialog() {
        if (this.mErrorDialog != null && this.mErrorDialog.isShowing()) {
            this.mErrorDialog.dismiss();
            this.mErrorDialog.cancel();
            this.mErrorDialog = null;
        }
    }

    public void cancelToastErrorDialog() {
        cancelErrorDialog();
    }

}
